﻿using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Finance
{
    public class Finance_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Finance/Finance_List.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;
        protected int userStatus;
        public IUsersService _users { get; set; }
        protected string keywords = string.Empty;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.View.ToString()); //检查权限           
        }
        // GET: /admin/finance/

        public IActionResult Index()
        {
            this.keywords = Request.Query["keywords"];
            string pagenum = Request.Query["PageNum"];
            this.userStatus = CMSRequest.GetQueryInt("ddlUserId", 11, HttpContext);
            if (int.TryParse(pagenum, out this.pageSize))
            {
                if (this.pageSize > 0)
                {
                    Response.Cookies.Append("finance_page_size", this.pageSize.ToString());
                }
            }
            else
            {
                this.pageSize = GetPageSize(10); //每页数量
            }
            ViewBag.Keywords = this.keywords;
            ViewBag.PageNum = this.pageSize.ToString();
            ViewBag.userStatus = this.userStatus;
            List<SelectListItem> userListItems = new List<SelectListItem>();
            userListItems.Add(new SelectListItem() { Text = "请选择会员类型...", Value = "" });
            userListItems.Add(new SelectListItem() { Text = "游客", Value = "0" });//user_id=0
            userListItems.Add(new SelectListItem() { Text = "贵宾未激活", Value = "10" });//user_id>0 and is_pass=0
            userListItems.Add(new SelectListItem() { Text = "贵宾已激活", Value = "11" });//user_id>0 and is_pass=1
            ViewData["userListItems"] = userListItems;
            string strWhere = "where id>0";
            switch (this.userStatus)
            {
                case 0://游客
                    strWhere = strWhere + " and user_id=0";
                    break;
                case 10://贵宾未激活
                    strWhere = strWhere + " and user_id>0 and is_pass=0";
                    break;
                case 11://贵宾已激活
                    strWhere = strWhere + " and user_id>0 and is_pass=1";
                    break;
            }
            RptBind(strWhere + CombSqlTxt(keywords), "pass_time desc,id desc");
            return View(WEB_VIEW);
        }
        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and (user_name like '%" + _keywords + "%' or mobile like '%" + _keywords + "%' or email like '%" + _keywords + "%' or nick_name like '%" + _keywords + "%')");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            this.page = 1;
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            ViewData["list"] = _users.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            this.totalCount = _users.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "keywords={0}&page={1}", this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["finance_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion
        //从游客转为贵宾只能单向
        [HttpPost]
        public ActionResult SubmitAudit()
        {
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    if (_users.UpdateField(id, "user_id=id") > 0)
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "游客转为贵宾成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result=JscriptMsg("审核通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //锁定贵宾一切权益
        [HttpPost]
        public ActionResult SubmitLock()
        {
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    int status = _users.GetModel(id).is_lock;
                    if (status == 0)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                    if (_users.UpdateField(id, "is_lock="+status) > 0)
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "锁定贵宾成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result=JscriptMsg("审核通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //停止贵宾各种资金制度
        [HttpPost]
        public ActionResult SubmitJiangjin()
        {
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    int status = _users.GetModel(id).is_jiangjin;
                    if (status == 0)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                    if (_users.UpdateField(id, "is_jiangjin="+status) > 0)
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "设置奖金成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result=JscriptMsg("审核通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //禁止贵宾推荐人
        [HttpPost]
        public ActionResult SubmitShare()
        {
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    int status = _users.GetModel(id).is_share;
                    if (status == 0)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                    if (_users.UpdateField(id, "is_share="+status) > 0)
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "设置分享成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result=JscriptMsg("审核通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
        //设置为空点位不向上级产生资金
        [HttpPost]
        public ActionResult SubmitKong()
        {
            ChkAdminLevel("finance_list", CMSEnums.ActionEnum.Audit.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            //批量删除
            JObject jobject = JObject.Parse(Request.Form["json"]);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    int status = _users.GetModel(id).is_kong;
                    if(status==0)
                    {
                        status = 1;
                    }
                    else
                    {
                        status = 0;
                    }
                    if (_users.UpdateField(id, "is_kong="+status) > 0)
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Audit.ToString(), "设置空点成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string result=JscriptMsg("审核通过" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(result);
        }
    }
}
